package com.pmmaster.admin.controllers;

import com.pmmaster.common.api.Result;
import com.pmmaster.common.utils.Captcha;
import com.pmmaster.common.utils.RedisUtil;
import com.pmmaster.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/")
public class CommonController {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private FileService fileService;

    private static String token = "token";

    @Value("${upload_base_dir}")
    private String upload_base_dir;

    @Value("${static_path}")
    private String static_path;

    @RequestMapping(value = "/verify/{type}", method = {RequestMethod.GET, RequestMethod.POST})
    public void verify(HttpServletRequest request, HttpServletResponse response, @PathVariable String type) throws Exception {
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //实例生成验证码对象
        Captcha instance = new Captcha();
        redisUtil.set(request.getParameter(token), instance.getCode(), 600);
        instance.write(response.getOutputStream());
    }

    @RequestMapping(value = "/upload/{type}", method = {RequestMethod.POST})
    @ResponseBody
    public Result upload(MultipartFile file, @PathVariable String type) {
        //获取文件对象
        if (file == null) {
            return Result.failed("请选择要上传的图片");
        }
        type = type == null ? "default" : type;
        return fileService.upload(file, upload_base_dir, static_path, type);
    }
}
